<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\components;
use Yii;
 
/**
 * Description of Share
 *
 * @author shuai
 */
class croppic  {
      public static function crop()  {

        $imgUrl =  Lcms::getHost(). $_POST['imgUrl'];
// original sizes
        $imgInitW = $_POST['imgInitW'];
        $imgInitH = $_POST['imgInitH'];
// resized sizes
        $imgW = $_POST['imgW'];
        $imgH = $_POST['imgH'];
// offsets
        $imgY1 = $_POST['imgY1'];
        $imgX1 = $_POST['imgX1'];
// crop box
        $cropW = $_POST['cropW'];
        $cropH = $_POST['cropH'];
// rotation angle
        $angle = $_POST['rotation'];

        $jpeg_quality = 100;

      //  $output_filename = "uploads/temp/croppedImg_" . rand();

// uncomment line below to save the cropped image in the same location as the original image.
//$output_filename = dirname($imgUrl). "/croppedImg_".rand();

        $what = getimagesize($imgUrl);
       // var_dump(strtolower($what['mime']));exit;
        switch (strtolower($what['mime'])) {
            case 'image/png':
                $img_r = imagecreatefrompng($imgUrl);
                $source_image = imagecreatefrompng($imgUrl);
                $type = '.png';
                break;
            case 'image/jpeg':
                $img_r = imagecreatefromjpeg($imgUrl);
                $source_image = imagecreatefromjpeg($imgUrl);
                //error_log("jpg");
                $type = '.jpeg';
                break;
            case 'image/gif':
                $img_r = imagecreatefromgif($imgUrl);
                $source_image = imagecreatefromgif($imgUrl);
                $type = '.gif';
                break;
            default: die('image type not supported');
        }
            

      $save_path = Yii::getAlias('@webroot').'/public/Uploads/';
      //文件保存目录URL
     $save_url =  Lcms::getWeb(). 'public/Uploads/';
     
       $dir_name='caijian';
                        $save_path .= $dir_name . "/";
                        $save_url .= $dir_name . "/";
                        if (!file_exists($save_path)) {
                       //    echo $save_path;exit;
                                mkdir($save_path);
                        }
      $ymd = date("Ymd");
                $save_path .= $ymd . "/";
                $save_url .= $ymd . "/";
                if (!file_exists($save_path)) {
                        mkdir($save_path);
                }
                //新文件名
                $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) .  $type;
                //移动文件
                $file_path = $save_path . $new_file_name;
              $save_url.=$new_file_name;
            
//Check write Access to Directory

        if (!is_writable(dirname($file_path))) {
            $response = Array(
                "status" => 'error',
                "message" => 'Can`t write cropped File'
            );
        } else {

            // resize the original image to size of editor
            $resizedImage = imagecreatetruecolor($imgW, $imgH);
            imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW, $imgH, $imgInitW, $imgInitH);
            // rotate the rezized image
            $rotated_image = imagerotate($resizedImage, -$angle, 0);
            // find new width & height of rotated image
            $rotated_width = imagesx($rotated_image);
            $rotated_height = imagesy($rotated_image);
            // diff between rotated & original sizes
            $dx = $rotated_width - $imgW;
            $dy = $rotated_height - $imgH;
            // crop rotated image to fit into original rezized rectangle
            $cropped_rotated_image = imagecreatetruecolor($imgW, $imgH);
            imagecolortransparent($cropped_rotated_image, imagecolorallocate($cropped_rotated_image, 0, 0, 0));
            imagecopyresampled($cropped_rotated_image, $rotated_image, 0, 0, $dx / 2, $dy / 2, $imgW, $imgH, $imgW, $imgH);
            // crop image into selected area
            $final_image = imagecreatetruecolor($cropW, $cropH);
            imagecolortransparent($final_image, imagecolorallocate($final_image, 0, 0, 0));
            imagecopyresampled($final_image, $cropped_rotated_image, 0, 0, $imgX1, $imgY1, $cropW, $cropH, $cropW, $cropH);
            // finally output png image
            //imagepng($final_image, $output_filename.$type, $png_quality);
            imagejpeg($final_image, $file_path, $jpeg_quality);
            $response = Array(
                "status" => 'success',
                "url" =>$save_url
            );
        }
        print json_encode($response);
    }

    public static function save(){
           //文件保存目录路径
    $save_path = Yii::getAlias('@webroot').'/public/Uploads/';
      //文件保存目录URL
     $save_url =  Lcms::getWeb(). 'public/Uploads/';
     
     
                     $dir_name='linshi';
                        $save_path .= $dir_name . "/";
                        $save_url .= $dir_name . "/";
                        if (!file_exists($save_path)) {
                       //    echo $save_path;exit;
                                mkdir($save_path);
                        }
                   
       //最大文件大小
        $max_size = 1024*1024*1;
         ///  $imagePath = "uploads/";

	$allowedExts = array("gif", "jpeg", "jpg", "png", "GIF", "JPEG", "JPG", "PNG");
	$temp = explode(".", $_FILES["img"]["name"]);
	$extension = end($temp);
	
	//Check write Access to Directory

	if(!is_writable($save_path)){
		$response = Array(
			"status" => 'error',
			"message" => 'Can`t upload File; no write Access'
		);
		print json_encode($response);
		return;
	}
	 $file_size = $_FILES['img']['size'];
         $file_name = $_FILES['img']['name'];
         //检查文件大小
        if ($file_size > $max_size) {
                self::alert("上传文件大小超过限制。");
        }
       $extension= strtolower($extension);
       //// echo $extension;exit;
	if ( in_array($extension, $allowedExts))
	  {
	  if ($_FILES["img"]["error"] > 0)
		{
			 $response = array(
				"status" => 'error',
				"message" => 'ERROR Return Code: '. $_FILES["img"]["error"],
			);			
		}
	  else
		{
              
            
            //获得文件扩展名
                $temp_arr = explode(".", $file_name);
                $file_ext = array_pop($temp_arr);
                $file_ext = trim($file_ext);
                $file_ext = strtolower($file_ext);
              
              $ymd = date("Ymd");
                $save_path .= $ymd . "/";
                $save_url .= $ymd . "/";
                if (!file_exists($save_path)) {
                        mkdir($save_path);
                }
                //新文件名
                $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
                //移动文件
                $file_path = $save_path . $new_file_name;
              $save_url.=$new_file_name;
              
			
	      $filename = $_FILES["img"]["tmp_name"];
		  list($width, $height) = getimagesize( $filename );

		  move_uploaded_file($filename, $file_path);

		  $response = array(
			"status" => 'success',
			"url" =>$save_url,
			"width" => $width,
			"height" => $height
		  );
		  
		}
	  }
	else
	  {
	   $response = array(
			"status" => 'error',
			"message" => '上传文件不符合要求,请重新上传',
		);
	  }
	  
	  print json_encode($response);
      }
      
      static function alert($str){
            $response = array(
			"status" => 'error',
			"message" =>$str,
		);
	  print json_encode($response);exit;
      }
      
      
}
